
//  ChatTableViewImageCell.m
//  供销宝
//
//  Created by 金晶 on 17/2/14.
//  Copyright © 2017年 金晶. All rights reserved.
//

#import "ChatTableViewImageCell.h"
#import "UIImageView+WebCache.h"
#import "NSString+TimeFormat.h"

@interface ChatTableViewImageCell ()

@property(nonatomic,strong)ChatMessage *ChatMessage;

@end

@implementation ChatTableViewImageCell

+ (UITableViewCell *)cellWithTableView:(ChatTableView *)tableView messageModel:(ChatMessage *)model withmasTop:(CGFloat)masTop {
    
    static NSString *imageCellIndentifier = @"imageCellIndentifier";
    
    ChatTableViewImageCell *cell = [tableView dequeueReusableCellWithIdentifier:imageCellIndentifier];
    
    
    if(!cell){
        cell = [[ChatTableViewImageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:imageCellIndentifier];
    }
    cell.ChatMessage = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
   
    if(model.splitTime.length > 0) {
        NSString *dateStr = [model.splitTime format];
        cell.timeLabel.text = dateStr;
        cell.timeLabel.hidden = NO;
    }else {
        cell.timeLabel.hidden =YES;
    }
    
    if(model.msgSourceType==CHAT_MSG_RECV) {
        
        cell.logoImage.frame=CGRectMake(10, masTop, 40, 40);
        
        BOOL isShowNickName = NO;
        if ([tableView.chatProtocol.chatDelegate respondsToSelector:@selector(isShowNickName)]) {
            isShowNickName = [tableView.chatProtocol.chatDelegate isShowNickName];
        }
        
        if (isShowNickName) {
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.right+8, masTop, 150, [cell returnNameTop:isShowNickName]-3);
        }else{
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.right+8, masTop, 0, 0);
        }
        cell.nickNameLabel.textAlignment = NSTextAlignmentLeft;

        
        NSURL *url = [NSURL URLWithString:model.mediaPath];
        [cell.contextBack sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"photo"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (!error)
            {
                //做压缩处理后期还是在上面改造一下，把压缩图存起来，暂时不做了
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    UIImage *simage = scaleImageToMaxSize(image);
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        cell.contextBack.image = simage;
                        
                    });
                });
            }}];
//        [cell.contextBack sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"photo"]];
        
        cell.imageViewMask.image = [[UIImage imageNamed:@"wechatback1"] stretchableImageWithLeftCapWidth:10 topCapHeight:25];
        cell.imageViewMask.frame = CGRectMake(0, 0, model.imageWidth, model.imageHeight);
        
        cell.contextBack.frame=CGRectMake(LEFT_WITH, masTop+[cell returnNameTop:isShowNickName], model.imageWidth, model.imageHeight);
        cell.contextBack.layer.mask = cell.imageViewMask.layer;
        [cell.contentView addSubview:cell.contextBack];
        
    }else if(model.msgSourceType ==CHAT_MSG_SEND) {
        
        cell.logoImage.frame=CGRectMake(kScreenWidth-10-40, masTop, 40, 40);
        
        BOOL isShowNickName = NO;
        if ([tableView.chatProtocol.chatDelegate respondsToSelector:@selector(isShowNickName)]) {
            isShowNickName = [tableView.chatProtocol.chatDelegate isShowNickName];
        }
        
        if (isShowNickName) {
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.left-150-8, masTop, 150, [cell returnNameTop:isShowNickName]-3);
        }else{
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.left-150-8, masTop, 0, 0);
        }
        cell.nickNameLabel.textAlignment = NSTextAlignmentRight;
        
        //要判断图片的长和宽
        NSString* imageUrl=LocalImagePath(model.toFriendid,model.contentPath);
        NSString *realThumbPath = [ImageAddition thumbPath:imageUrl];

        UIImage *image = [UIImage imageWithContentsOfFile:realThumbPath];

        CGSize imageSize=[Common imageShowSize:image];
        cell.imageViewMask.image = [[UIImage imageNamed:@"wechatback2"] stretchableImageWithLeftCapWidth:10 topCapHeight:25];
        cell.imageViewMask.frame = CGRectMake(0, 0, imageSize.width, imageSize.height);
        
        cell.contextBack.frame=CGRectMake(kScreenWidth-LEFT_WITH-imageSize.width, masTop+[cell returnNameTop:isShowNickName], imageSize.width, imageSize.height);
        
        cell.contextBack.image = image;
        
        cell.contextBack.layer.mask = cell.imageViewMask.layer;
        [cell.contentView addSubview:cell.contextBack];
        //正在发送状态
        if(model.messageState ==CHAT_MSG_SENDING){
            
            [cell.acview startAnimating];
            [cell.acview setHidden:NO];
            [cell.retryButton setHidden:YES];
            
            [cell.acview mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contextBack);
                make.right.mas_equalTo(cell.contextBack.mas_left).offset(-10);
            }];
        }else if (model.messageState ==CHAT_MSG_SEND_NONE) {
            
            //未发送状态
            [cell.retryButton mas_makeConstraints:^(MASConstraintMaker *make) {
                [cell.acview setHidden:YES];
                [cell.retryButton setHidden:NO];
                
                make.centerY.equalTo(cell.contextBack);
                make.right.mas_equalTo(cell.contextBack.mas_left).offset(-10);
            }];
        }else {
            [cell.acview setHidden:YES];
            [cell.retryButton setHidden:YES];
        }
    }
    
    return cell;
}

//如果图片正在加载。不会点击图片放大
- (void)handleSingleTap:(UITapGestureRecognizer *)sender {
   
    !self.imageClickBlock?:self.imageClickBlock();
}

//功能待定
- (void)showMenuControllerInView:(ChatTableViewImageCell *)inView
                          bgView:(UIView *)supView {
    
    self.coversImageView.hidden=NO;
    
    [self becomeFirstResponder];
    
    UIMenuItem *copyTextItem1 = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyTextSender1)];
    UIMenuItem *copyTextItem2 = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(copyTextSender2)];
    
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setTargetRect:supView.frame inView:inView];
    [menu setArrowDirection:UIMenuControllerArrowDefault];
    [menu setMenuItems:@[copyTextItem1,copyTextItem2]];
    
    [menu setMenuVisible:YES animated:YES];
}

#pragma mark 剪切板代理方法
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    
    if (action == @selector(copyTextSender1)) {
        return true;
    } else  if (action == @selector(copyTextSender2)) {
        return true;
    } else {
        return false;
    }
}   

//图片复制时，有点特殊
- (void)copyTextSender1 {
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    NSString *imageUrl = nil;
    
    if(self.ChatMessage.msgSourceType ==CHAT_MSG_SEND) {
        imageUrl=LocalImagePath(self.ChatMessage.toFriendid,self.ChatMessage.contentPath);
    }else {
        //复制好友小图时。需要加载大图。
        imageUrl = @"test.png";
    }
//    pasteboard.URLs = @[[NSURL URLWithString:imageUrl],[NSURL URLWithString:self.ChatMessage.imageUrl]];
}

- (void)copyTextSender2 {
    
    !self.removeChatInfoBlock?:self.removeChatInfoBlock(self.ChatMessage);
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

@end
